package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@RestController     //开启事务
@RequestMapping("/dish")
@Slf4j
@Api(tags = "口味相关接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增菜品接口")
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //保存菜品成功要清空redis中的数据（1.清空全部的数据 2.精确清除）
        //1.清空全部的数据
       /* Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //2.精确清除
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //分页
        Page<Dish> pageinfo = new Page<>(page, pageSize);
        //模糊查询
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        //模糊查询
        lqw.like(!StringUtils.isEmpty(name), Dish::getName, name);
        //排序
        lqw.orderByDesc(Dish::getUpdateTime);
        //查询
        dishService.page(pageinfo, lqw);

        /*Page<DishDto> resultPage = new Page<>();
        //把pageinfo中的数据拷贝到resultPage中，除了records；
        BeanUtils.copyProperties(pageinfo, resultPage, "records");
        List<Dish> records = pageinfo.getRecords();
        ArrayList<DishDto> dishDtoList = new ArrayList<>();

        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            //设置分类名称
            Category category = categoryService.getById(record.getCategoryId());
            dishDto.setCategoryName(category.getName());

            dishDtoList.add(dishDto);
        }
        resultPage.setRecords(dishDtoList);
        return R.success(resultPage);*/

        //返回的结果包含categoryName
        Page<DishDto> resultPage = new Page<>();
        //把pageinfo的数据拷贝到pageinfo除啦records
        BeanUtils.copyProperties(pageinfo, resultPage, "records");
        List<Dish> records = pageinfo.getRecords();

        resultPage.setRecords(records.stream().map(record -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            //设置分类名称
            Category category = categoryService.getById(record.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList()));

        return R.success(resultPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //保存菜品成功要清空redis中的数据（1.清空全部的数据 2.精确清除）
        //1.清空全部的数据
       /* Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //2.精确清除
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    /**
     * 批量删除
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        System.out.println(ids);
        dishService.deleteAll(ids);
        return R.success("删除成功");
    }

    /**
     * 批量启售/停售
     */
   /* @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status,Long[] ids) {
        List<Long> longs = Arrays.asList(ids);
        List<Dish> dishes = dishService.listByIds(longs);

        for (Dish dish : dishes) {
            dish.setStatus(status);
        }
        dishService.updateBatchById(dishes);
        return R.success("修改成功");
    }*/
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, @RequestParam("ids") List<Long> ids) {
        log.info("批量操作数据：{}", ids);
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(status);
        }
        dishService.updateBatchById(dishes);
        return R.success("修改成功");
    }

    /**
     * 套餐菜品
     */
    @GetMapping("list")
    public R<List<DishDto>> select(Dish dish) {
        //查数据之前先查询redis中是否有数据，有数据直接返回
        List<DishDto> dishDtos = null;
        //设置key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //查询redis中是否有数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            //直接返回
            return R.success(dishDtos);
        }
        //打印日志
        log.info("套餐菜品：{}", dish);

        //构造查询条件
        LambdaQueryWrapper<Dish> dishlqw = new LambdaQueryWrapper<>();
        dishlqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加查询条件，查询状态为1的菜品
        dishlqw.eq(Dish::getStatus, 1);
        //添加排序条件
        dishlqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishlqw);

        //查询口味信息
        dishDtos = list.stream().map(item -> {
            DishDto dishDto = new DishDto();
            //基本信息的拷贝
            BeanUtils.copyProperties(item, dishDto);
            //设置菜品的口味信息
            LambdaUpdateWrapper<DishFlavor> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> list1 = dishFlavorService.list(wrapper);
            dishDto.setFlavors(list1);

            return dishDto;
        }).collect(Collectors.toList());

        //没有数据在查询数据库，再将查询到的数据存入redis中,并设置过期时间为60分钟
        redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);
        return R.success(dishDtos);

    }

}
